//
//  ScxqVC.swift
//  Auscultation
//
//  Created by 来 on 2020/12/22.
//

import UIKit

class ScxqVC: BaseVC {
    
    var id: String = ""
    var data: [String: Any]!
    
    var scrollView: UIScrollView!
    
    var tzzx: UILabel!
    
    var ph_view: UIScrollView!
    var ph_view_i: UIImageView!
    var ph_r: bzxV!
    
    // 播放
    var play_button: UIButton!
    // 时间
    var play_time: UILabel!
    var play_time_all: UILabel!
    // 进度
    var play_line: UISlider!
    
    var player: LGFAudioPlayer!
    
    var wavPath: String = ""
    var duration: Int = 0
    
    var isPlay: Bool = false
    
    var hzxi_v: UIView!
    
    // 患者
    var hzxm: UILabel!
    var jhzxm: UILabel!
    var csrq: UILabel!
    var xb: UILabel!
    var mzh: UILabel!
    var ybh: UILabel!
    var sfzh: UILabel!
    var sjh: UILabel!
    var lxdz: UILabel!
    var sg: UILabel!
    var tz: UILabel!
    var sfzj: UILabel!
    var tw: UILabel!
    var phcd: UILabel!
    var xycjcs: UILabel!
    var sfss: UILabel!
    var lczdxx: UILabel!
    var bz: UILabel!
    
    // AI辅助筛查参考
    var fzscck_v: UIView!
    var fzscck_error: UIView!
    var fzscck_fxz: UIView!
    var bzxfgl: UILabel!
    var ybycgl_n: UILabel!
    var ycqy_l: UILabel!
    var vsd_c: UIView!
    var asd_c: UIView!
    var pda_c: UIView!
    var ps_c: UIView!
    var tof_c: UIView!
    var vsd_n: UILabel!
    var asd_n: UILabel!
    var pda_n: UILabel!
    var ps_n: UILabel!
    var tof_n: UILabel!
    
    // 筛查结论
    var zzysscjl_b_v: UIView!
    var ypqk: UILabel!
    var ypbz: UILabel!

    override func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated)
        player.paused()
    }
    
    deinit {
        debugPrint("LGFAudioPlayer 已释放")
        player?.stop()
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        initUI()
        player = LGFAudioPlayer()
        player.delegate = self
        ph_view.contentSize = CGSize.init(width: (ph_view.lgf_Height * 30720 / 350) - 25, height: ph_view.lgf_Height)
        getData()
        NotificationCenter.default.addObserver(self, selector: #selector(ScxqVC.getData), name: NSNotification.Name(rawValue: "ReloadScxqVC"), object: nil)
    }
    
    @objc func getData() {
        let paramet: [String: String] = [
            "encryptedData": "zFoamlSX95gBI7S05+e6HakuGltzhbckTNdkY0yZ2hU="
        ]
        EWERequest.lgf("screening/" + id, paramet, .get) { [weak self] (data) in
            self?.data = data as? [String : Any]
            self?.tzzx.text = (data["no"] as? String) ?? ""
            // 音频
            self?.ph_view_i.lgf_setImage(((data["screeningDetail"] as? [String: Any])?["wavPowerPics"] as? String) ?? "")
            self?.play_line.maximumValue = Float((((data["screeningDetail"] as? [String: Any])?["duration"] as? Int) ?? 0) / 1000)
            self?.play_time_all.text = self?.player.getAllTime(Int(self?.play_line.maximumValue ?? 0) * 1000) ?? "00:00"
            self?.wavPath = EWEUrl.File_URL + (((data["screeningDetail"] as? [String: Any])?["wavPath"] as? String) ?? "")
            // 患者
            self?.lxdz.text = "联系地址：" + (((data["patient"] as? [String: Any])?["address"] as? String) ?? "")
            self?.hzxm.text = "患者姓名：" + (((data["patient"] as? [String: Any])?["name"] as? String) ?? "")
            self?.sjh.text = "手机号：" + (((data["patient"] as? [String: Any])?["phone"] as? String) ?? "")
            self?.xb.text = "性别：" + ((((data["patient"] as? [String: Any])?["gender"] as? String) ?? "") == "1" ? "男" : "女")
            self?.jhzxm.text = "监护者姓名：" + (((data["patient"] as? [String: Any])?["guardian"] as? String) ?? "")
            self?.csrq.text = "出生日期：" + (((data["patient"] as? [String: Any])?["birthday"] as? Int) ?? 0).description.lgf_TimeStampToDate().lgf_TimeStr("yyyy-MM-dd")
            self?.tw.text = "体位：" + ((data["position"] as? String) ?? "")
            self?.phcd.text = "配合程度：" + ((data["coordinate"] as? String) ?? "")
            self?.sfzj.text = "是否镇静：" + ((data["calm"] as? Int ?? 0) == 0 ? "否" : "是")
            self?.sg.text = "身高：" + ((data["height"] as? String) ?? "")
            self?.tz.text = "体重：" + ((data["weight"] as? String) ?? "")
            self?.xycjcs.text = "心音采集场所：" + ((data["site"] as? String) ?? "")
            self?.sfss.text = "是否手术：" + ((data["operation"] as? String) ?? "")
            self?.lczdxx.text = "临床诊断信息：" + ((data["descn"] as? String) ?? "")
            self?.mzh.text = "门诊号：" + ((data["patientNo"] as? String) ?? "")
            self?.bz.text = "备注：" + ((data["remark"] as? String) ?? "")
            
            // 筛查状态：10：筛查中；20：筛查完成；30：待确定
            let status = (data["status"] as? Int ?? 0)
            if status == 10 {
                self?.zzysscjl_b_v.isHidden = false
            } else {
                self?.zzysscjl_b_v.isHidden = true
                let screeningAssess = data["screeningAssess"] as! [String: Any]
                let conditions = ((screeningAssess["conditions"] as? Int) ?? 0)
                if conditions < 3 {
                    self?.ypqk.text = ["正常", "异常", "待确定"][conditions]
                }
                self?.ypbz.text = "备注：" + ((screeningAssess["remake"] as? String) ?? "")
            }
            
            // 分析状态：10：分析中；20：分析完成
            let aiStatus = (data["aiStatus"] as? Int ?? 0)
            if aiStatus == 10 {
                self?.fzscck_v.isHidden = true
                self?.fzscck_fxz.isHidden = false
                self?.fzscck_error.isHidden = true
            } else if aiStatus == 20 {
                self?.fzscck_v.isHidden = false
                self?.fzscck_fxz.isHidden = true
                self?.fzscck_error.isHidden = true
                let screeningAnalysis = data["screeningAnalysis"] as! [String: Any]
                self?.ycqy_l.text = ((screeningAnalysis["abnormalArea"] as? String) ?? "")
                self?.ybycgl_n.text = ((screeningAnalysis["abnormalProbability"] as? String) ?? "")
                self?.vsd_n.text = ((screeningAnalysis["vsdProbability"] as? String) ?? "")
                self?.asd_n.text = ((screeningAnalysis["asdProbability"] as? String) ?? "")
                self?.pda_n.text = ((screeningAnalysis["pdaProbability"] as? String) ?? "")
                self?.ps_n.text = ((screeningAnalysis["psProbability"] as? String) ?? "")
                self?.tof_n.text = ((screeningAnalysis["tofProbability"] as? String) ?? "")
                let vsd = self?.vsd_n.text!.replacingOccurrences(of: "%", with: "") ?? "0"
                let asd = self?.asd_n.text!.replacingOccurrences(of: "%", with: "") ?? "0"
                let pda = self?.pda_n.text!.replacingOccurrences(of: "%", with: "") ?? "0"
                let ps = self?.ps_n.text!.replacingOccurrences(of: "%", with: "") ?? "0"
                let tof = self?.tof_n.text!.replacingOccurrences(of: "%", with: "") ?? "0"
                self?.vsd_c.snp.updateConstraints({ (make) in
                    make.width.equalTo((UIDevice.lgf_ScreenW - 156) * (CGFloat(Int(vsd) ?? 0) / 100.0) + 6.0)
                })
                self?.asd_c.snp.updateConstraints({ (make) in
                    make.width.equalTo((UIDevice.lgf_ScreenW - 156) * (CGFloat(Int(asd) ?? 0) / 100.0) + 6.0)
                })
                self?.pda_c.snp.updateConstraints({ (make) in
                    make.width.equalTo((UIDevice.lgf_ScreenW - 156) * (CGFloat(Int(pda) ?? 0) / 100.0) + 6.0)
                })
                self?.ps_c.snp.updateConstraints({ (make) in
                    make.width.equalTo((UIDevice.lgf_ScreenW - 156) * (CGFloat(Int(ps) ?? 0) / 100.0) + 6.0)
                })
                self?.tof_c.snp.updateConstraints({ (make) in
                    make.width.equalTo((UIDevice.lgf_ScreenW - 156) * (CGFloat(Int(tof) ?? 0) / 100.0) + 6.0)
                })
            } else {
                self?.fzscck_v.isHidden = true
                self?.fzscck_fxz.isHidden = true
                self?.fzscck_error.isHidden = false
            }
            // source
        } _: { (error) in
            SVProgressHUD.showError(error)
        }
    }
    
    // 更多信息
    @objc func s_ckgd(_ sender: UITapGestureRecognizer) {
        if sender.view?.lgf_ViewName == "收拢" {
            sender.view?.lgf_ViewName = "展开"
            hzxi_v.snp.updateConstraints { (make) in
                make.height.equalTo(540)
            }
        } else {
            sender.view?.lgf_ViewName = "收拢"
            hzxi_v.snp.updateConstraints { (make) in
                make.height.equalTo(100)
            }
        }
        scrollView.lgf_AutoContentSize(40)
    }
    
    @objc func s_txzzysscjl() {
        let vc = ZzscjlVC()
        vc.id = (self.data["id"] as? String ?? "")
        self.navigationController?.show(vc, sender: self)
    }

}

extension ScxqVC: UIScrollViewDelegate {
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        if !scrollView.isTracking && !scrollView.isDragging && !scrollView.isDecelerating {
            return
        }
        let value = CGFloat(self.play_line.maximumValue) * (scrollView.contentOffset.x) / (scrollView.contentSize.width - scrollView.lgf_Width)
        player.seek(Float(value))
        play_time.text = "/" + player.getAllTime(Int(value) * 1000)
        play_line.setValue(Float(value), animated: false)
        paused()
    }
    
    func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
        if !scrollView.isDragging {
            if isPlay {
                resume()
            }
        }
    }

    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        if isPlay {
            resume()
        }
    }
    
    @objc func playNow(_ sender: UIButton) {
        if wavPath.count == 0 {
            return
        }
        if player.state == .playing {
            isPlay = false
            paused()
        } else if player.state == .paused {
            resume()
        } else {
            play()
        }
    }
    
    func run(_ value: Float) {
        self.play_line!.value = value
        self.scroll(value)
        self.play_time.text = "/" + player.getTime()
    }
    
    func scroll(_ value: Float) {
        if self.play_line.maximumValue == 0 {
            return
        }
        self.ph_view.setContentOffset(CGPoint.init(x: CGFloat(value) / CGFloat(self.play_line.maximumValue) * (self.ph_view.contentSize.width - self.ph_view.lgf_Width), y: 0), animated: false)
    }
    
    func paused() {
        player.paused()
        play_button.setBackgroundImage(#imageLiteral(resourceName: "bofang"), for: .normal)
    }
    
    func stop() {
        isPlay = false
        play_time.text = "/00:00"
        play_line.setValue(0, animated: false)
        ph_view.setContentOffset(CGPoint.zero, animated: false)
        player?.stop()
        play_button.setBackgroundImage(#imageLiteral(resourceName: "bofang"), for: .normal)
    }
    
    func resume() {
        isPlay = true
        player.resume()
        play_button.setBackgroundImage(#imageLiteral(resourceName: "zanting"), for: .normal)
    }
    
    func play() {
        isPlay = true
        player.playOnLine(wavPath)
        play_button.setBackgroundImage(#imageLiteral(resourceName: "zanting"), for: .normal)
    }

    @objc func s_end(_ sender: UISlider) {
        if isPlay {
            resume()
        }
    }
    @objc func s_changed(_ sender: UISlider) {
        player.seek(sender.value)
        play_time.text = "/" + player.getAllTime(Int(sender.value) * 1000)
        scroll(sender.value)
        paused()
    }
    @objc func s_tap(_ sender: UITapGestureRecognizer) {
        let touchPoint = sender.location(in: play_line)
        let value = Float(play_line.maximumValue - play_line.minimumValue) * Float(touchPoint.x / play_line.lgf_Width)
        scroll(value)
        play_line.setValue(value, animated: true)
        player.seek(value)
    }
    
}

extension ScxqVC: LGFAudioPlayerDelegate {
    func LGFAudioPlayerState(_ player: STKAudioPlayer) {
        self.play_line.maximumValue = Float(player.duration)
    }
    
    func LGFAudioPlayerRun(_ player: STKAudioPlayer) {
        self.run(Float(player.progress))
    }
    
    func LGFAudioPlayerStop(_ player: STKAudioPlayer) {
        self.stop()
    }
}
